package com.zhangxin.aiInterview.manager.knoewlege_base_api;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zhangxin.aiInterview.manager.knoewlege_base_api.dto.ExamQuestionWrapper;
import com.zhangxin.aiInterview.model.enums.ExamQuestionTypeEnum;

import java.util.ArrayList;
import java.util.List;

/**
 * 将笔试题json字符串解析成实体类
 */
public class ExamQuestionParser {

    /**
     * 将json字符串解析为java对象
     * @param json
     * @return
     */
    public static ExamQuestionWrapper parseExamQuestions(String json) {
        String cleanJson = json.replace("```json", "").replace("```", "").trim();
        System.out.println(cleanJson);
        JSONArray root = JSONUtil.parseArray(cleanJson);
        ExamQuestionWrapper wrapper = new ExamQuestionWrapper();

        List<ExamQuestionWrapper.ChoiceQuestion> choiceList = new ArrayList<>();
        List<String> shortAnswerList = new ArrayList<>();
        List<String> programmingList = new ArrayList<>();

        for (Object obj : root) {
            JSONObject node = (JSONObject) obj;
            int type = node.getInt("type");
            JSONArray questions = node.getJSONArray("question");

            if (type == ExamQuestionTypeEnum.CHOICE.getValue()) { // 选择题
                for (Object qObj : questions) {
                    JSONObject q = (JSONObject) qObj;
                    ExamQuestionWrapper.ChoiceQuestion cq = new ExamQuestionWrapper.ChoiceQuestion();
                    cq.setTitle(q.getStr("title"));

                    List<ExamQuestionWrapper.ChoiceQuestion.Option> options = new ArrayList<>();
                    JSONArray opts = q.getJSONArray("option");
                    for (Object optObj : opts) {
                        JSONObject opt = (JSONObject) optObj;
                        ExamQuestionWrapper.ChoiceQuestion.Option option = new ExamQuestionWrapper.ChoiceQuestion.Option();
                        option.setKey(opt.getStr("key"));
                        option.setValue(opt.getStr("value"));
                        options.add(option);
                    }

                    cq.setOptionList(options);
                    choiceList.add(cq);
                }
            } else if (type == ExamQuestionTypeEnum.SHORT_ANSWER.getValue()) { // 问答题/简答题
                for (Object qObj : questions) {
                    shortAnswerList.add(qObj.toString());
                }
            } else if (type == ExamQuestionTypeEnum.PROGRAMMING.getValue()) { // 编程题
                for (Object qObj : questions) {
                    programmingList.add(qObj.toString());
                }
            }
        }

        wrapper.setChoiceQuestions(choiceList);
        wrapper.setShortAnswerQuestions(shortAnswerList);
        if (!programmingList.isEmpty()) {
            wrapper.setProgrammingQuestions(programmingList);
        }

        return wrapper;
    }
}